package problems

// 1108
// https://leetcode-cn.com/problems/defanging-an-ip-address/
func DeFangIPAddr(address string) string {
	var newAddress []byte
	for i := 0; i < len(address); i++ {
		if address[i] == '.' {
			newAddress = append(newAddress, '[', '.', ']')
		} else {
			newAddress = append(newAddress, address[i])
		}
	}
	return string(newAddress)
}

// 1143
// https://leetcode-cn.com/problems/longest-common-subsequence/
func LongestCommonSubsequence(text1 string, text2 string) int {
	m, n := len(text1), len(text2)
	dp := make([][]int, m+1)
	for i := 0; i <= m; i++ {
		dp[i] = make([]int, n+1)
	}
	for i := 1; i <= m; i++ {
		for j := 1; j <= n; j++ {
			if text1[i-1] == text2[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				if dp[i][j-1] > dp[i-1][j] {
					dp[i][j] = dp[i][j-1]
				} else {
					dp[i][j] = dp[i-1][j]
				}
			}
		}
	}
	return dp[m][n]
}

// 1190
// https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses/
func ReverseParentheses(s string) string {
	stack, indexs := make([]rune, 0), make([]int, 0)
	reverseStack := func(left int) {
		right := len(stack) - 1
		stack[left] = stack[right]
		left++
		right--
		for left < right {
			stack[left], stack[right] = stack[right], stack[left]
			left++
			right--
		}
		stack, indexs = stack[:len(stack)-1], indexs[:len(indexs)-1]
	}
	for _, v := range s {
		switch v {
		case ')':
			reverseStack(indexs[len(indexs)-1])
		case '(':
			stack, indexs = append(stack, v), append(indexs, len(stack))
		default:
			stack = append(stack, v)
		}
	}

	return string(stack)
}
